package com.oracle.application.config;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oracle.application.entity.Orders;
import com.oracle.application.entity.Paylog;
import com.oracle.application.entity.vo.PayAsyncVo;
import com.oracle.application.entity.vo.PayVo;
import com.oracle.application.service.IOrdersService;
import com.oracle.application.service.IPaylogService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@ConfigurationProperties(prefix = "payconfig")
@Component
@Data
@Slf4j
public class PayConfig {

    @Autowired
    private IPaylogService iPaylogService;

    @Autowired
    private IOrdersService iOrdersService;

    private String app_id;
    private String payGateway;
    private String notify_url;
    private String return_url;
    private String publicKey;
    private String privateKey;


    public String doPay(PayVo payVo,Integer orderId){

        AlipayClient client=new DefaultAlipayClient(payGateway,app_id,privateKey,"json","utf-8",publicKey,"RSA2");
        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setReturnUrl(return_url);
        request.setNotifyUrl(notify_url);
        Paylog paylog = new Paylog();
        paylog.setPayprice(new BigDecimal(payVo.getTotal_amount()));
        paylog.setOrdersn(payVo.getOut_trade_no());
        paylog.setCreatedate(LocalDateTime.now());
        paylog.setModifydate(LocalDateTime.now());
        paylog.setOrders(orderId);
        paylog.setContent("订单编号为:"+payVo.getOut_trade_no()+"在"+LocalDateTime.now()+"正在向支付宝发起支付请求,发起的支付金额为:"+payVo.getTotal_amount());
        paylog.setSatus(2);
        paylog.setMember(1);
        this.iPaylogService.save(paylog);
        payVo.setPassback_params(paylog.getId()+"");
        request.setBizContent(JSONObject.toJSONString(payVo));
        String resulPage=null;
     try {
          resulPage=  client.pageExecute(request).getBody();
         return resulPage;
     }catch (AlipayApiException e){
         e.printStackTrace();
     }

        return resulPage;
    }
    //验证签名,并处理一些核心业务
    public boolean verifysignture(PayAsyncVo payAsyncVo){
        Map<String,String> params=JSONObject.parseObject(JSONObject.toJSONString(payAsyncVo),Map.class);
        try {
            boolean b= AlipaySignature.rsaCheckV1(params,publicKey,"utf-8","RSA2");
            if(b){
                //验签通过
                log.info("异步回调验签");
                //开启业务检查处理
                Integer payLogid=Integer.parseInt(payAsyncVo.getPassback_params());
                Paylog paylog=   this.iPaylogService.getById(payLogid);
                if(!payAsyncVo.getOut_trade_no().equals(paylog.getOrdersn())){
                    return false;
                }
                //请求时支付的金额 与 支付的金额不一致时 也返回false
                if(!payAsyncVo.getInvoice_amount().equals(paylog.getPayprice().toString())){
                    return false;
                }
                //变更订单状态:3种方式:分布式锁  悲观锁  数据库中直接更改
                //payAsyncVo.getTrade_status();//先判断支付成功与否
                System.out.println(payAsyncVo.getTrade_status()+"===========>>>>>");
                if("TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())){
                    String content= paylog.getContent();
                    StringBuffer payLoginBuffer=new StringBuffer(content);
                    payLoginBuffer.append("|订单编号为:"+payAsyncVo.getOut_trade_no()+"在"+LocalDateTime.now()+"成功支付");
                    paylog.setContent(payLoginBuffer.toString());
                    paylog.setSatus(1);
                    this.iPaylogService.updateById(paylog);
                    if(this.iOrdersService.updateOrderSatus(payAsyncVo.getOut_trade_no())>0){
                        return true;
                    }
                    return false;
                }
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
        }


        return  false;
    }

    //由于同步回调后参数不完整需要根据回调的请求
    public boolean returnfySignture(PayAsyncVo payAsyncVo){
        String orderSn=payAsyncVo.getOut_trade_no();
        Orders orders=new Orders();
        orders.setOrdersn(orderSn);
        QueryWrapper wrapper=new QueryWrapper(orders);
        orders=this.iOrdersService.getOne(wrapper);
       if (orders.getOrderstatus()==1){
           return true;
       }
       return false;
    }

}
